<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: sap<songaiping@hrbjjhh.com>
// +----------------------------------------------------------------------------

namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo 商户模型
 */
class MerchantModel extends BaseModel {

    /* 自动验证规则 */
    protected $_validate = array(
        array('merchant_name', 'require', '商户名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('merchant_name', 'checkName', '商户名称已经存在', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
    	array('merchant_name', '1,30', '商户名称长度不能超过30个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('sort', 'number', '排序必须为数字', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('sort', '1,5', '排序长度不能大于5个字符', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH),
		array('merchant_phone', 'checkPhone', '商户手机号格式不正确或已经存在', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
    	array('create_time', NOW_TIME, self::MODEL_INSERT),
    	array('update_time', NOW_TIME, self::MODEL_BOTH),
    	array('status', '1', self::MODEL_INSERT),
    );
    
    /**
     * @todo 检测手机号格式
     * @param  string $merchant_phone 用户名
     * @return boolean ture|false
     */
    protected function checkPhone($merchant_phone){
		$merchant_id = (int)I('merchant_id');
    	//判断是否存在
		$map = array();
		if(!preg_match("/^1[3-8][0-9]{9}$/", $merchant_phone)){
			return false;
		}else{
			$map['merchant_id'] = array('neq',$merchant_id);
		}
		$map['merchant_phone'] = $merchant_phone;
    	$map['status'] = array('gt',-1);
    	if($this->where($map)->find()){
    		return false;
    	}else{
    		return true;
		}
    }
    
	/**
     * @todo 检测名称是否存在
     * @param  string $login_name 用户名
     * @return boolean          ture - 未重名，false - 已重名
     */
    protected function checkName($merchant_name){
    	$merchant_id = (int)I('merchant_id');
    	//判断是否存在
    	$map = array();
    	if($merchant_id != 0){
    		$map['merchant_id'] = array('neq',$merchant_id);
    	}
    	$map['merchant_name'] = $merchant_name;
    	$map['status'] = array('gt',-1);
    	if($this->where($map)->find()){
    		return false;
    	}
    	return true;
    }

    /**
     * @todo 新增或更新一个商户
     * @return boolean fasle 失败 ， int  成功 返回商户ID
     * @author sap
     * @since 2015-8-17
     */
    public function update(){
        /* 获取数据对象 */
    	$data = $this->create($_POST);
        if(empty($data)){
            return false;
        }
        
        /* 添加或更新数据 */
        if(empty($data['merchant_id'])){ //新增数据
            $merchant_id = $this->add();
            if(!$merchant_id){
                $this->error = '新增商户出错！';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新商户出错！';
                return false;
            }else{
            	$merchant_id = $data['merchant_id'];
            }
        }
        S('sys_merchant_',null);//清除缓存
        //内容添加或更新完成
        return $merchant_id;
    }

    /**
     * @todo 商户详情
     * @param int $merchant_id 商户id
     * @param string $field 查询字段
     * @return false|array
     * @author sap
     */
    public function merchantShow($merchant_id=0,$field=''){
    	//获取数据
    	$merchant_id = (int)$merchant_id;
    	if($merchant_id == 0){
    		$this->error = '请正确操作';
    		return false;
    	}
    	$map = array();//初始化查询条件
    	//查询条件
    	$map['merchant_id'] = $merchant_id;
    	$map['status'] = array('gt',-1);
    	//返回值
    	return $this->where($map)->field($field)->find();
    }
    
    /**
     * @todo 商户列表
     * @param array $where 查询条件数组
     * @param string $field 查询字段
     * @param string $orderby 排序
     * @return false|array 商户列表数组
     * @author sap
     */
    public function getMerchantList($where = array(),$field= '',$orderby='sort asc,merchant_id desc'){
    	return $this->where($where)->field($field)->order($orderby)->select();
    }
    
    /**
     * @todo    商户权限设置
     */
    public function merchantUpdate(){

        $member_id = (int)I('member_id');
        if($member_id == 0){
            $this->error = '参数错误';
            return false;
        }
        $rules =  implode(',', I('rules'));
        $auth = M('auth_merchant');
        $member = $auth->where(array('member_id' => $member_id))->getField('member_id');
        // 添加修改操作
        if($member > 0){
            $save = $auth->where(array('member_id' => $member_id))->setField('rules', $rules);
            if($save === false){
                $this->error = '修改失败';
                return false;
            }
        }else{
            $data = array(
                'member_id' => $member_id,
                'rules' => $rules,
                'create_time' => NOW_TIME,
            );
            $add = $auth->add($data);
            if($add === false){
                $this->error = '添加失败';
                return false;
            }
        }
        return true;
    }
    
    /**
     * @todo    删除员工的商户权限
     */
    public function merchantAuthDel($id){
        if(empty($id)){
            $this->error = '请选择员工';
            return false;
        }
        $where['member_id'] = array('in', $id);
        $del = M('auth_merchant')->where($where)->delete();
        if($del === false){
            $this->error = '删除失败';
            return false;            
        }else{
            return true;
        }
    }
    
    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function getPk(){
    	return 'merchant_id';
    }
}
